//
//  ViewController.m
//  iPhoneX
//
//  Created by liaoyp on 2017/12/11.
//  Copyright © 2017年 liaoyp. All rights reserved.
//

#import "NNNewsHomeController.h"
#import "AFNetworking/AFNetworking/AFNetworking.h"
#import "NNNewsTableViewCell.h"
#import "NNNotify.h"
#import "NNNews.h"
#import "Store.h"

/// iPhone X预定地址
NSString *const KKiPhoneXReserveUrl = @"https://reserve-prime.apple.com/HK/zh_HK/reserve/iPhoneX";

@interface NNNewsHomeController ()<UIActionSheetDelegate>

@property (nonatomic ,strong) NSArray<NNNews *> *newsList;
@property (nonatomic ,strong) NSArray<Store *> *storeList;
@property (nonatomic ,strong) UITextView *tableViewHeaderView;
@property (nonatomic ,assign) NSInteger loadStoreIndex;
@property (nonatomic ,assign) BOOL isLoading;

@end

@implementation NNNewsHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.tableView.rowHeight = 88;
    [self.tableView registerClass:[NNNewsTableViewCell class] forCellReuseIdentifier:@"NNNewsTableViewCell"];
    
    _tableViewHeaderView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
    _tableViewHeaderView.backgroundColor = [UIColor redColor];
    _tableViewHeaderView.textAlignment = NSTextAlignmentCenter;
    self.tableView.tableHeaderView = _tableViewHeaderView;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
}

- (IBAction)autoCliecked:(UIBarButtonItem *)sender {
    
    if (!self.storeList) {
        [self showMessage:@"先获取店铺信息"];
        return;
    }
    
    if (self.loadStoreIndex > (self.storeList.count - 1)) {
        self.loadStoreIndex = 0;
    }    
    Store *store = self.storeList[self.loadStoreIndex];
    
    _tableViewHeaderView.text = [NSString stringWithFormat:@"正在查询:%@-%@店",store.city,store.storeName];
    NSLog(@"request:%@",_tableViewHeaderView.text);
    [self sendIPhoneXRequestWithStorecode:store.storeNumber regioncode:@"HK" needStock:YES complteHandler:^(NSArray<NNNews *> *newsList) {
        
        if (newsList.count > 0) {
            NNNews *news = [newsList firstObject];
            _tableViewHeaderView.text = [NSString stringWithFormat:@"成功查询到：%@-%@-%@",store.city,store.storeName, news.Name];
            
            // 需要抢购256的
            BOOL canReserve = news.CanReserve;
            if (canReserve) {
//                NSString *meesage = [NSString stringWithFormat:@"成功查询到：%@-%@-%@ 有货，快去抢购",store.city,store.storeName, news.Name];
//                [self triggerLocalNotifation:meesage];
            }
            
            if (canReserve && [news.Name containsString:@"256GB"]) {
                
                NSString *meessage = [NSString stringWithFormat:@"成功抢到：%@-%@-%@",store.city,store.storeName, news.Name];
                //NSString *meesage = [NSString stringWithFormat:@"成功查询到：%@-%@-%@ 有货，快去抢购",store.city,store.storeName, news.Name];
                [self triggerLocalNotifation:meessage];
                [self showMessage:meessage];
                
                return;
            }
        }
        self.loadStoreIndex += 1;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self autoCliecked:nil];
        });
    }];
}

- (void)triggerLocalNotifation:(NSString *)notiyMessage
{
    NNNotify *notify = [[NNNotify alloc] init];
    notify.eventName = notiyMessage;
    notify.objectId = @([NSDate date].timeIntervalSince1970).stringValue;
    notify.isRepeat = NO;
    notify.fireDate = [NSDate date];
    [NNNotify sendiOS10LocalNotification:notify];
}

- (IBAction)appHKStoreClicked:(UIBarButtonItem *)sender {
    //
    if (!self.storeList) {
        [self showMessage:@"正在获取店铺信息"];
        [self startHKStoresRequest];
        return;
    }
    
    UIActionSheet *sheetView = [[UIActionSheet alloc] initWithTitle:@"苹果店铺选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
    [self.storeList enumerateObjectsUsingBlock:^(Store * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.storeName) {
            [sheetView addButtonWithTitle:obj.storeName];
        }
    }];
    [sheetView showInView:self.view];
}


- (void)showMessage:(NSString *)message
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"警告" message:message delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: nil];
    [alertView show];
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([actionSheet cancelButtonIndex] == buttonIndex) {
        return;
    }
    Store *store = self.storeList[buttonIndex];
    self.title = store.storeName;
    
    [self sendIPhoneXRequestWithStorecode:store.storeNumber regioncode:@"HK" needStock:NO complteHandler:^(NSArray<NNNews *> *news) {
        self.newsList = news;
        [self.tableView reloadData];
    }];
}


- (void)startHKStoresRequest
{
    NSMutableURLRequest* request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:@"https://reserve-prime.apple.com/HK/zh_HK/reserve/iPhoneX/stores.json" parameters:nil error:NULL];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSLog(@"HTTP Response Body: %@", responseObject);
        if (!error) {
            NSArray<NSDictionary<NSString *,NSString *> *> *jsonData = [responseObject objectForKey:@"stores"];
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:jsonData.count];
            [jsonData enumerateObjectsUsingBlock:^(NSDictionary<NSString *,NSString *> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                Store *store = [[Store alloc] init];
                [obj enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
                    @try {
                        [store setValue:obj forKeyPath:key];
                    } @catch (NSException *exception) {}
                }];
                [array addObject:store];
            }];
            self.storeList = [array copy];
        }
    }];
    [dataTask resume];
}

- (void)sendIPhoneXRequestWithStorecode:(NSString *)storecode regioncode:(NSString *)regioncode needStock:(BOOL)stock complteHandler:(void (^)(NSArray<NNNews *> * news))completionHandler;
{
    // Create manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // Create request
    NSDictionary* URLParameters = @{
                                    @"storecode":storecode,
                                    @"regioncode":@"HK",
                                    @"onlyshowavailability":stock ? @"true":@"false",
                                    };
    NSMutableURLRequest* request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"http://ir.weip.tech/Home/GetStoreiPhoneList" parameters:URLParameters error:NULL];
    
    // Add Headers
    [request setValue:@"UM_distinctid=16044dd93555aa-07dccaf2430286-17386d57-fa000-16044dd935651d; CNZZDATA1260363899=1245570524-1512983740-%7C1512983740" forHTTPHeaderField:@"Cookie"];
    
    // Fetch Request
     NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSLog(@"HTTP Response Body: %@", responseObject);
        
        if (!error) {
            NSArray<NSDictionary<NSString *,NSString *> *> *jsonData = [responseObject objectForKey:@"Data"];
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:jsonData.count];
            [jsonData enumerateObjectsUsingBlock:^(NSDictionary<NSString *,NSString *> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NNNews *news = [[NNNews alloc] init];
                [obj enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
                    @try {
                        [news setValue:obj forKey:key];
                    } @catch (NSException *exception) {}
                }];
                [array addObject:news];
            }];
            
            NSArray *responseArray = [array copy];
            if (completionHandler) {
                completionHandler(responseArray);
            }
        }
    }];
    [dataTask resume];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.newsList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NNNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NNNewsTableViewCell" forIndexPath:indexPath];
    NNNews *news = self.newsList[indexPath.row];
    NSMutableString *mutabString = [NSMutableString string];
    [mutabString appendString:news.RetailName];
    [mutabString appendString:@"\n"];
    [mutabString appendString:news.Name];
    [mutabString appendString:@"  "];
    [mutabString appendString:news.SKU];
    [mutabString appendString:@"\n"];
    [mutabString appendString:news.Price];
    cell.messageLabel.text = mutabString;
    
    if (news.CanReserve) {
        cell.backgroundColor = [UIColor greenColor];
    }
    else
    {
        cell.backgroundColor = [UIColor lightGrayColor];
    }
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
